using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using DocumentCreationSystem.Services;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// Ollama模型下载对话框
    /// </summary>
    public partial class OllamaModelDownloadDialog : Window
    {
        private readonly ILogger<OllamaModelDownloadDialog> _logger;
        private readonly OllamaModelPullService _pullService;
        private CancellationTokenSource? _cancellationTokenSource;
        private bool _isDownloading = false;

        // 预设模型映射
        private readonly Dictionary<string, string> _presetModels = new()
        {
            { "bge-m3 (向量模型)", "bge-m3" },
            { "llama3.2:3b", "llama3.2:3b" },
            { "llama3.2:1b", "llama3.2:1b" },
            { "qwen2.5:7b", "qwen2.5:7b" },
            { "qwen2.5:3b", "qwen2.5:3b" },
            { "qwen2.5:1.5b", "qwen2.5:1.5b" },
            { "gemma2:2b", "gemma2:2b" },
            { "phi3:mini", "phi3:mini" }
        };

        public OllamaModelDownloadDialog()
        {
            InitializeComponent();

            // 获取服务
            var serviceProvider = App.ServiceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<OllamaModelDownloadDialog>>();
            _pullService = serviceProvider.GetRequiredService<OllamaModelPullService>();

            InitializeUI();
        }

        /// <summary>
        /// 设置Ollama服务地址
        /// </summary>
        public void SetOllamaUrl(string url)
        {
            if (!string.IsNullOrEmpty(url))
            {
                OllamaUrlTextBox.Text = url;
            }
        }

        private void InitializeUI()
        {
            // 设置预设模型选择事件
            PresetModelsComboBox.SelectionChanged += PresetModels_SelectionChanged;
            
            // 添加日志
            AppendLog("Ollama模型下载工具已启动");
            AppendLog("请选择要下载的模型，然后点击开始下载");
        }

        private void PresetModels_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (PresetModelsComboBox.SelectedItem is ComboBoxItem item)
            {
                var selectedText = item.Content.ToString();
                if (selectedText == "自定义...")
                {
                    CustomModelTextBox.IsEnabled = true;
                    CustomModelTextBox.Focus();
                }
                else
                {
                    CustomModelTextBox.IsEnabled = false;
                    CustomModelTextBox.Text = "";
                }
            }
        }

        private async void TestConnection_Click(object sender, RoutedEventArgs e)
        {
            var ollamaUrl = OllamaUrlTextBox.Text.Trim();
            if (string.IsNullOrEmpty(ollamaUrl))
            {
                UpdateStatus("请输入Ollama服务地址", false);
                return;
            }

            TestConnectionButton.IsEnabled = false;
            UpdateStatus("正在测试连接...", true);

            try
            {
                using var httpClient = new HttpClient();
                httpClient.Timeout = TimeSpan.FromSeconds(10);
                
                var response = await httpClient.GetAsync($"{ollamaUrl.TrimEnd('/')}/api/tags");
                
                if (response.IsSuccessStatusCode)
                {
                    UpdateStatus("连接成功！", false);
                    AppendLog($"成功连接到Ollama服务: {ollamaUrl}");
                }
                else
                {
                    UpdateStatus($"连接失败: HTTP {response.StatusCode}", false);
                    AppendLog($"连接失败: HTTP {response.StatusCode}");
                }
            }
            catch (Exception ex)
            {
                UpdateStatus($"连接失败: {ex.Message}", false);
                AppendLog($"连接失败: {ex.Message}");
                _logger.LogError(ex, "测试Ollama连接失败");
            }
            finally
            {
                TestConnectionButton.IsEnabled = true;
            }
        }

        private async void Download_Click(object sender, RoutedEventArgs e)
        {
            if (_isDownloading)
            {
                // 如果正在下载，则取消下载
                _cancellationTokenSource?.Cancel();
                return;
            }

            var modelName = GetSelectedModelName();
            if (string.IsNullOrEmpty(modelName))
            {
                UpdateStatus("请选择或输入模型名称", false);
                return;
            }

            var ollamaUrl = OllamaUrlTextBox.Text.Trim();
            if (string.IsNullOrEmpty(ollamaUrl))
            {
                UpdateStatus("请输入Ollama服务地址", false);
                return;
            }

            await StartDownloadAsync(ollamaUrl, modelName);
        }

        private async Task StartDownloadAsync(string ollamaUrl, string modelName)
        {
            _isDownloading = true;
            _cancellationTokenSource = new CancellationTokenSource();
            
            // 更新UI状态
            DownloadButton.Content = "取消下载";
            DownloadButton.Style = (Style)FindResource("CancelButtonStyle");
            TestConnectionButton.IsEnabled = false;
            PresetModelsComboBox.IsEnabled = false;
            CustomModelTextBox.IsEnabled = false;
            OllamaUrlTextBox.IsEnabled = false;
            
            DownloadProgressBar.Visibility = Visibility.Visible;
            DownloadProgressBar.IsIndeterminate = false;
            DownloadProgressBar.Value = 0;

            AppendLog($"开始下载模型: {modelName}");
            UpdateStatus("正在下载...", true);

            try
            {
                // 检查模型是否已存在
                var exists = await _pullService.IsModelExistsAsync(ollamaUrl, modelName);
                if (exists)
                {
                    var result = MessageBox.Show(
                        $"模型 {modelName} 已存在，是否重新下载？",
                        "模型已存在",
                        MessageBoxButton.YesNo,
                        MessageBoxImage.Question);
                    
                    if (result != MessageBoxResult.Yes)
                    {
                        AppendLog("用户取消了下载");
                        return;
                    }
                }

                // 创建进度回调
                var progress = new Progress<OllamaModelPullProgress>(OnDownloadProgress);

                // 开始下载
                var success = await _pullService.PullModelAsync(
                    ollamaUrl, 
                    modelName, 
                    progress, 
                    _cancellationTokenSource.Token);

                if (success)
                {
                    UpdateStatus("下载完成！", false);
                    AppendLog($"模型 {modelName} 下载成功！");
                    
                    // 显示完成对话框
                    MessageBox.Show(
                        $"模型 {modelName} 下载完成！\n\n您现在可以在AI模型配置中使用此模型。",
                        "下载完成",
                        MessageBoxButton.OK,
                        MessageBoxImage.Information);
                    
                    // 显示关闭按钮
                    CloseButton.Visibility = Visibility.Visible;
                }
                else if (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    UpdateStatus("下载失败", false);
                    AppendLog($"模型 {modelName} 下载失败");
                }
            }
            catch (OperationCanceledException)
            {
                UpdateStatus("下载已取消", false);
                AppendLog("用户取消了下载");
            }
            catch (Exception ex)
            {
                UpdateStatus($"下载失败: {ex.Message}", false);
                AppendLog($"下载异常: {ex.Message}");
                _logger.LogError(ex, $"下载模型 {modelName} 时发生异常");
            }
            finally
            {
                // 恢复UI状态
                _isDownloading = false;
                DownloadButton.Content = "开始下载";
                DownloadButton.Style = (Style)FindResource("ModernButtonStyle");
                TestConnectionButton.IsEnabled = true;
                PresetModelsComboBox.IsEnabled = true;
                OllamaUrlTextBox.IsEnabled = true;
                
                if (PresetModelsComboBox.SelectedItem is ComboBoxItem item && 
                    item.Content.ToString() == "自定义...")
                {
                    CustomModelTextBox.IsEnabled = true;
                }
                
                DownloadProgressBar.Visibility = Visibility.Collapsed;
            }
        }

        private void OnDownloadProgress(OllamaModelPullProgress progress)
        {
            Dispatcher.Invoke(() =>
            {
                StatusTextBlock.Text = progress.Status;
                ProgressTextBlock.Text = progress.ProgressText;
                
                if (progress.Total > 0)
                {
                    DownloadProgressBar.IsIndeterminate = false;
                    DownloadProgressBar.Value = progress.ProgressPercentage;
                }
                else
                {
                    DownloadProgressBar.IsIndeterminate = true;
                }

                if (progress.IsError)
                {
                    AppendLog($"错误: {progress.ErrorMessage}");
                }
                else if (!string.IsNullOrEmpty(progress.ProgressText))
                {
                    AppendLog(progress.ProgressText);
                }

                // 滚动到底部
                LogTextBox.ScrollToEnd();
            });
        }

        private string GetSelectedModelName()
        {
            if (PresetModelsComboBox.SelectedItem is ComboBoxItem item)
            {
                var selectedText = item.Content.ToString();
                if (selectedText == "自定义...")
                {
                    return CustomModelTextBox.Text.Trim();
                }
                else if (_presetModels.TryGetValue(selectedText, out var modelName))
                {
                    return modelName;
                }
            }
            return "";
        }

        private void UpdateStatus(string message, bool isWorking)
        {
            StatusBarText.Text = message;
            if (isWorking)
            {
                StatusBarText.Text += " ...";
            }
        }

        private void AppendLog(string message)
        {
            var timestamp = DateTime.Now.ToString("HH:mm:ss");
            var logMessage = $"[{timestamp}] {message}\n";
            
            Dispatcher.Invoke(() =>
            {
                LogTextBox.AppendText(logMessage);
                LogTextBox.ScrollToEnd();
            });
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (_isDownloading)
            {
                _cancellationTokenSource?.Cancel();
            }
            else
            {
                DialogResult = false;
                Close();
            }
        }

        private void Close_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = true;
            Close();
        }

        protected override void OnClosed(EventArgs e)
        {
            _cancellationTokenSource?.Cancel();
            _cancellationTokenSource?.Dispose();
            base.OnClosed(e);
        }
    }
}
